package com.dc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dc.common.DateUtil;
import com.dc.common.ResponseResultVO;
import com.dc.entity.WorkOrder;
import com.dc.entity.WorkOrderFile;
import com.dc.entity.ro.RepairWorkOrderRO;
import com.dc.entity.vo.RepairVO;
import com.dc.enums.OrderType;
import com.dc.enums.OrderTypeEng;
import com.dc.mapper.WorkOrderFileMapper;
import com.dc.mapper.WorkOrderMapper;
import com.dc.service.RepairWorkOrderService;
import com.dc.util.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.dc.common.ResponseResultVO.checkParameterIsNotNull;

@Service
public class RepairWorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, WorkOrder> implements RepairWorkOrderService {
    @Resource
    private WorkOrderMapper workOrderMapper;
    @Resource
    private WorkOrderFileMapper workOrderFileMapper;
    @Resource
    private RedisUtil redisUtil;

    @Override
    @Transactional
    public ResponseResultVO insertRepairWorkOrder(RepairWorkOrderRO ro) {

        List<WorkOrder> workOrders = workOrderMapper.selectList(new LambdaQueryWrapper<WorkOrder>()
                .eq(WorkOrder::getSerialNumber, ro.getSerialNumber())
                .eq(WorkOrder::getType, 2).eq(WorkOrder::getStatus, 0));
        if (!workOrders.isEmpty() && workOrders.size() > 0) {
            return ResponseResultVO.failResult(String.format("设备【%s】,已提交报修,请勿重复提交!", ro.getSerialNumber()));
        }

        LambdaQueryWrapper<WorkOrder> wrapper = new LambdaQueryWrapper<WorkOrder>()
                .eq(WorkOrder::getSerialNumber, ro.getSerialNumber())
                .eq(WorkOrder::getType, 0).eq(WorkOrder::getStatus, 0);
        WorkOrder workOrder = workOrderMapper.selectOne(wrapper);
        if (workOrder == null) {
            return ResponseResultVO.failResult(String.format("设备【%s】,暂未发现故障信息,无法报修!", ro.getSerialNumber()));
        }

        WorkOrder wo = new WorkOrder();
        wo.setStatus(2);
        int update = workOrderMapper.update(wo, wrapper);
        if (update < 1) {
            return ResponseResultVO.updateResult(update);
        }

        WorkOrder repairWorkOrder = new WorkOrder();
        BeanUtils.copyProperties(ro, repairWorkOrder);
        repairWorkOrder.setId(SnowflakeIdWorker.generateId());
        repairWorkOrder.setNumber(redisUtil.serialNumber("BX"));
        repairWorkOrder.setType(OrderType.REPAIR.getId());
        if (StringUtils.isNotBlank(ro.getRepairTime())) {
            repairWorkOrder.setRecTime(DateUtil.parseStrToDate(ro.getRepairTime(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        }
        if (CollectionUtils.isNotEmpty(ro.getFileIds())) {
            for (String path : ro.getFileIds()) {
                WorkOrderFile repairWorkOrderFile = new WorkOrderFile();
                repairWorkOrderFile.setId(SnowflakeIdWorker.generateId());
                repairWorkOrderFile.setWorkOrderId(repairWorkOrder.getId());
                repairWorkOrderFile.setFilePath(path);
                workOrderFileMapper.insert(repairWorkOrderFile);
            }
        }
        int i = workOrderMapper.insert(repairWorkOrder);
        if (i > 0) {
            if (!CommonCodeUtil.increasing(OrderTypeEng.REPAIR.getName())) {
                //如果缓存为空，则查数据库再插入到redis
                Integer integer = workOrderMapper.selectCount(new QueryWrapper<WorkOrder>().lambda().eq(WorkOrder::getType, OrderType.FIRE.getId()));
                redisUtil.set(OrderTypeEng.REPAIR.getName(), 0 == integer ? 1 : integer);
            }
        }
        return ResponseResultVO.insertResult(i);
    }

    @Override
    @Transactional
    public ResponseResultVO updateRepairWorkOrder(RepairWorkOrderRO ro) {
        checkParameterIsNotNull(String.valueOf(ro.getId()), "id不能为空");
        WorkOrder repairWorkOrder = new WorkOrder();
        BeanUtils.copyProperties(ro, repairWorkOrder);
        workOrderFileMapper.delete(new QueryWrapper<WorkOrderFile>().lambda().eq(WorkOrderFile::getWorkOrderId, ro.getId()));
        if (CollectionUtils.isNotEmpty(ro.getFileIds())) {
            for (String path : ro.getFileIds()) {
                WorkOrderFile repairWorkOrderFile = new WorkOrderFile();
                repairWorkOrderFile.setId(SnowflakeIdWorker.generateId());
                repairWorkOrderFile.setWorkOrderId(repairWorkOrder.getId());
                repairWorkOrderFile.setFilePath(path);
                workOrderFileMapper.insert(repairWorkOrderFile);
            }
        }
        return ResponseResultVO.updateResult(workOrderMapper.updateById(repairWorkOrder));
    }

    @Override
    @Transactional
    public ResponseResultVO deleteRepairWorkOrder(String ids) {
        checkParameterIsNotNull(ids, "id不能为空");
        List<String> idList = Arrays.asList(ids.split(","));
        workOrderFileMapper.delete(new QueryWrapper<WorkOrderFile>().lambda().in(WorkOrderFile::getWorkOrderId, idList));
        int deleteBatchIds = workOrderMapper.deleteBatchIds(idList);
        if (deleteBatchIds > 0) {
            redisUtil.diminishing(OrderTypeEng.REPAIR.getName(), deleteBatchIds);
        }
        return ResponseResultVO.deleteResult(deleteBatchIds);
    }

    @Override
    public ResponseResultVO selectRepairWorkOrderList(RepairWorkOrderRO ro) {
        Page page = new Page<Map<String, Object>>(ro.getCurrentPage(), ro.getPageSize());
        QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
        //是否是H5
        if (StringUtils.isNotBlank(ro.getClient()) && "H5".equalsIgnoreCase(ro.getClient())) {
            queryWrapper.lambda().eq(WorkOrder::getReportUserId, UserUtil.getUserId());
        }
        queryWrapper.lambda().eq(WorkOrder::getType, OrderType.REPAIR.getId());
        queryWrapper.lambda().in(CollectionUtils.isNotEmpty(ro.getIds()), WorkOrder::getId, ro.getIds());
        queryWrapper.orderBy(StringUtils.isNotBlank(ro.getOrderByColumn()), "asc".equalsIgnoreCase(ro.getIsAsc()) ? true : false, StringUtils.toLine(ro.getOrderByColumn()));
        queryWrapper.lambda().like(StringUtils.isNotBlank(ro.getNumber()), WorkOrder::getNumber, ro.getNumber());
        queryWrapper.lambda().like(StringUtils.isNotBlank(ro.getDeviceModel()), WorkOrder::getDeviceModel, ro.getDeviceModel());
        queryWrapper.lambda().like(StringUtils.isNotBlank(ro.getSerialNumber()), WorkOrder::getSerialNumber, ro.getSerialNumber());
        queryWrapper.lambda().eq(null != ro.getReportUserId(), WorkOrder::getReportUserId, ro.getReportUserId());
        queryWrapper.lambda().eq(null != ro.getStatus(), WorkOrder::getStatus, ro.getStatus());
        queryWrapper.lambda().like(StringUtils.isNotBlank(ro.getDeviceName()), WorkOrder::getDeviceName, ro.getDeviceName());
        queryWrapper.lambda().eq(StringUtils.isNotBlank(ro.getRegionName()), WorkOrder::getRegionName, ro.getRegionName());

        queryWrapper.lambda().like(StringUtils.isNotBlank(ro.getReportUserName()), WorkOrder::getReportUserName, ro.getReportUserName());
        //上报时间区间查询
        if (StrUtil.isNotBlank(ro.getCreateTime()) && StrUtil.isNotBlank(ro.getCreateEndTime())) {
            queryWrapper.apply("date_format (create_time,'%Y-%m-%d') >= date_format('" + ro.getCreateTime() + "','%Y-%m-%d')");
            queryWrapper.apply("date_format (create_time,'%Y-%m-%d') <= date_format('" + ro.getCreateEndTime() + "','%Y-%m-%d')");
        } else {
            queryWrapper.apply(StrUtil.isNotBlank(ro.getCreateTime()),
                    "date_format (create_time,'%Y-%m-%d') = date_format('" + ro.getCreateTime() + "','%Y-%m-%d')");
        }
        queryWrapper.lambda().orderByDesc(WorkOrder::getCreateTime);
        Page<WorkOrder> pageData = workOrderMapper.selectPage(page, queryWrapper);
        List<RepairVO> fireVOS = ListBeanUtils.listCopyMapper(pageData.getRecords(), WorkOrder.class, RepairVO.class);
        List<WorkOrderFile> repairWorkOrderFiles = null;
        if (CollectionUtils.isNotEmpty(fireVOS)) {
            repairWorkOrderFiles = workOrderFileMapper.selectList(new QueryWrapper<WorkOrderFile>().lambda().in(WorkOrderFile::getWorkOrderId, fireVOS
                    .stream().map(RepairVO::getId).collect(Collectors.toList())));
            List<WorkOrderFile> repairWorkOrderFileList = repairWorkOrderFiles;
            fireVOS.forEach(s -> {
                s.setFiles(repairWorkOrderFileList.stream().filter(p -> p.getWorkOrderId().equals(s.getId())).collect(Collectors.toList()));
            });
        }
        ro.setTotalCount(workOrderMapper.selectCount(queryWrapper));
        return ResponseResultVO.resultPageList(fireVOS, ro);

    }

    @Override
    public void repairWorkOrderRecordExport(HttpServletResponse response, RepairWorkOrderRO ro) {
        ResponseResultVO roadReportForm = this.selectRepairWorkOrderList(ro);
        HashMap<String, Object> data = (HashMap<String, Object>) roadReportForm.getData();
        ExportUtil.exportExcelNew("报修记录", (List) data.get("list"), RepairVO.class, response);
    }
}
